﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Navigation;
using BootyShaker.Utils;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Dynamics.Joints;
using FarseerPhysics.Factories;
using FarseerPhysics.SamplesFramework;
using LineBatchTester;
using Microsoft.Advertising.Mobile.Xna;
using Microsoft.Phone.Applications.Common;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using System.Windows.Controls;

namespace BootyShaker
{
    public partial class GameScreen : UserControl
    {
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;
        Texture2D backgroundTexture;
        World World;
        //Body _rectangle;

        float dragStrength = 200f;

        DrawableAd drawableAd;
        private bool MergeOverlay;
        //ROT//SLXnaComponentSystem.GameComponentCollection components = new SLXnaComponentSystem.GameComponentCollection();

        public GameScreen(Action back)
        {
           // InitializeComponent();
            //AdComponent.Initialize("test_client");


            //AdRotatorInit();
            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;


            //_border = new Border(World, this, SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport);





            //joint = new FarseerPhysics.Dynamics.Joints.FixedLineJoint(_rectangle, _rectangle.Position, Vector2.Zero);
            //joint.MaxForce = 1000.0f * _rectangle.Mass;
            //joint.Enabled = true;
            // World.AddJoint(joint);
            //SetUserAgent(_rectanglejoint 100f, 100f);

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;
            AppSettings settings = new AppSettings();
            gravityRatio = (float)settings.GravityRatioSetting;
            dragStrength = (float)settings.DragStrengthSetting;
            MergeOverlay = settings.MergeOverlaySetting;
            AccelerometerHelper.Instance.ReadingChanged += new EventHandler<AccelerometerHelperReadingEventArgs>(OnAccelerometerHelperReadingChanged);
            startstop(true);


        }
        //ROT//
        //private void AdRotatorInit()
        //{

        //    AdRotatorXNAComponent.Initialize(spriteBatch);


        //    //Optional Local Hard coded Ad Provider setings

        //    //AdRotatorXNAComponent.Current.PubCenterAppId = "test_client";
        //    //AdRotatorXNAComponent.Current.PubCenterAdUnitId = "Image480_80";

        //    //AdRotatorXNAComponent.Current.AdDuplexAppId = "0";

        //    //AdRotatorXNAComponent.Current.InneractiveAppId = "DavideCleopadre_ClockAlarmNightLight_WP7";

        //    //AdRotatorXNAComponent.Current.MobFoxAppId = "474b65a3575dcbc261090efb2b996301";
        //    //AdRotatorXNAComponent.Current.MobFoxIsTest = true;

        //    //Specify where you want the Ad to display (based on the top left corner of the Ad)
        //    AdRotatorXNAComponent.Current.AdPosition = Vector2.Zero;

        //    //Optionally specify your own House Ad which will display if there is no network
        //    WriteableBitmap wb = Utils.Utils.OpenResourceImage("Advertising/DefaultAd/AdRotator.png");
        //    Texture2D houseAd = new Texture2D(SharedGraphicsDeviceManager.Current.GraphicsDevice, wb.PixelWidth, wb.PixelHeight);

        //    houseAd.SetData(Imaging.BGRAToRGBA(wb));

        //    AdRotatorXNAComponent.Current.DefaultHouseAdImage = houseAd;//contentManager.Load<Texture2D>(@"Advertising/DefaultAd/AdRotator.png");

        //    //Event handler to do something should the user click on your Default House Ad
        //    AdRotatorXNAComponent.Current.DefaultHouseAdClick += new AdRotatorXNAComponent.DefaultHouseAdClickEventHandler(Current_DefaultHouseAdClick);

        //    //Optionally specify the slide (popup) direction for the Ad
        //    //AdRotatorXNAComponent.Current.SlidingAdDirection = SlideDirection.Right;

        //    //Optionally Set the local configuration file used to set the default Ad Locations
        //    AdRotatorXNAComponent.Current.DefaultSettingsFileUri = "advertising/defaultAdSettings.xml";

        //    //Optionally set a URL from where to pull the configuration file down remotely each time the game is run
        //    AdRotatorXNAComponent.Current.SettingsUrl = "http://mysite.com/defaultAdSettings.xml";

        //    //Add the control to the XNA Component list which will display the ad
        //    //Note as this is XNA be sure to just to this for the game states you want it shown.

        //    components.Add(AdRotatorXNAComponent.Current);
        //    components.Initialize();
        //}
        ////AdRotatorXNAComponent adRotatorXNAComponent;
        //void Current_DefaultHouseAdClick()
        //{
        //    try
        //    {
        //        MessageBox.Show("You clicked on my Ad, thanks very much");
        //    }
        //    catch { }
        //}

        //Matrix _projection;
        //FixedDistanceJoint joint;
        public void OnNavigatedTo()
        {
            if (World == null)
            {
                World = new World(Vector2.Zero);
            }
            else
            {
                World.Clear();
            }
            World.Gravity = new Vector2(0f, 10f);
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);


            // TODO: use this.content to load your game content here
            LineBatch.Init(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            backgroundTexture = new Texture2D(SharedGraphicsDeviceManager.Current.GraphicsDevice, App.ShakeImageTransformed.PixelWidth, App.ShakeImageTransformed.PixelHeight, false, SurfaceFormat.Color);

            backgroundTexture.SetData(Imaging.BGRAToRGBA(App.ShakeImageTransformed));

            //WriteableBitmap wb = Utils.Utils.OpenResourceImage("Advertising/DefaultAd/AdRotator.png");
            //Texture2D houseAd = new Texture2D(SharedGraphicsDeviceManager.Current.GraphicsDevice, wb.PixelWidth, wb.PixelHeight);

            //houseAd.SetData(Imaging.BGRAToRGBA(wb));

            //AdRotatorXNAComponent.Current.DefaultHouseAdImage = houseAd;//contentManager.Load<Texture2D>(@"Advertising/DefaultAd/AdRotator.png");

            //AdRotatorXNAComponent.Current.components.Add(new AdRotatorXNAComponent(SharedGraphicsDeviceManager.Current.GraphicsDevice));
            //ROT// AdRotatorInit();
            if (App.IsTrial)
            {
                try
                {
                    //#if DEBUG
                    //                    AdComponent.Initialize("test_client");
                    //#else
                    AdComponent.Initialize(App.ApplicationID);

                    //#endif
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
                Microsoft.Xna.Framework.Rectangle rect = new Microsoft.Xna.Framework.Rectangle(0, 720, 480, 80);
                //#if DEBUG
                //                drawableAd = AdComponent.Current.CreateAd("Image480_80", rect, true);
                //#else
                drawableAd = AdComponent.Current.CreateAd(App.AdUnit.gamePage, rect, true);

                //#endif
                if (System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Contains("GPSLocationLatitude") && System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Contains("GPSLocationLongitude"))
                {
                    drawableAd.LocationLatitude = ((double)System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings["GPSLocationLatitude"]);
                    drawableAd.LocationLongitude = ((double)System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings["GPSLocationLongitude"]);
                    //drawableAd.Keywords = "";
                }


                drawableAd.AdRefreshed += new EventHandler(drawableAd_AdRefreshed);
                drawableAd.ErrorOccurred += new EventHandler<Microsoft.Advertising.AdErrorEventArgs>(drawableAd_ErrorOccurred);
            }
            else
            {
                // AdComponent.Current.Dispose();
            }


            App.DoNotCollide = false;
            foreach (ShakeObjectCtl so in App.shakeObjects)
            {

                foreach (ShakeObjectCtl obj in App.shakeObjects)
                {
                    if (obj != so)
                    {
                        Size sz = obj.getsize();
                        double radius1 = (sz.Width + sz.Height) / 6;
                        sz = so.getsize();
                        double radius2 = (sz.Width + sz.Height) / 6;
                        System.Windows.Point Location1 = new System.Windows.Point(obj.DesignLocation.X + obj.size.Width / 2, obj.DesignLocation.Y + obj.size.Height / 2);

                        System.Windows.Point Location2 = new System.Windows.Point(so.DesignLocation.X + so.size.Width / 2, so.DesignLocation.Y + so.size.Height / 2);

                        if (Util.Distance(Location1, Location2) / (radius1 + radius2) < 0.85)
                        {
                            App.DoNotCollide = true;
                        }

                    }
                }
            }

            foreach (ShakeObjectCtl so in App.shakeObjects)
            {
                so.LoadImage(SharedGraphicsDeviceManager.Current.GraphicsDevice, World);
                maxTextCount = Math.Max(maxTextCount, so.texturesList.Count);

                //joint.DampingRatio= 2f;
            }

           


            // Start the timer
            timer.Start();
            startstop(true);
            
        }



        private void drawableAd_ErrorOccurred(object sender, Microsoft.Advertising.AdErrorEventArgs e)
        {
            Debug.WriteLine("Ad error occurred!");
        }

        private void drawableAd_AdRefreshed(object sender, EventArgs e)
        {
            Debug.WriteLine("Ad refreshed!");
        }

        private int maxTextCount = 0;
        //Texture2D testTxt;

        public void OnNavigatedFrom()
        {
            // Stop the timer
            timer.Stop();


            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);
            startstop(false);

            if (App.IsTrial)
            {
                drawableAd.AdRefreshed -= new EventHandler(drawableAd_AdRefreshed);
                drawableAd.ErrorOccurred -= new EventHandler<Microsoft.Advertising.AdErrorEventArgs>(drawableAd_ErrorOccurred);
                AdComponent.Current.Enabled = false;
            }


            
        }




        private double GetDelta()
        {
            long tick = DateTime.UtcNow.Ticks;
            double delta = new TimeSpan(tick - lastTick).TotalSeconds;
            lastTick = tick;
            return delta;
        }


        private long lastTick;

        //private double lastrefreshprint;
        //private double deltaprint;
        //private double FPS;
        //private long framesprint;

        double TimeSinceLastRefresh = 0;
        //int MaxFPS = 100;

        //double second = 0;
        //int frames = 0;

        double delta;

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            // TODO: Add your update logic here

            delta = GetDelta();
            delta = e.ElapsedTime.TotalSeconds;
            TimeSinceLastRefresh += delta;
            //second += delta;

            //if (TimeSinceLastRefresh >= 1.0f / MaxFPS)
            //{
            //    RenderPositions();
            //    frames++;
            //    if (second > 1)
            //    {
            //        framesprint = frames;
            //        FPS = frames / second;
            //        textBlock1.Text = string.Format("FPS:{0}", FPS);

            //        second = 0;
            //        frames = 0;
            //    }
            //    lastrefreshprint = TimeSinceLastRefresh;
            //    deltaprint = delta;

            //    TimeSinceLastRefresh -= (1.0f / MaxFPS);

            //}

            World.Step(Math.Min((float)e.ElapsedTime.TotalSeconds, (1f / 30f)));

            //foreach (ShakeObject so in App.shakeObjects)
            //{
            //    so.Movement(delta);

            //}
            //GameTime gt = new GameTime(e.TotalTime, e.ElapsedTime);
            //AdRotatorXNAComponent.Current.Update(gt);

            processMouse();
            //ROT//components.Update(e.ElapsedTime, e.TotalTime);
            if (App.IsTrial)
            {
                AdComponent.Current.Update(e.ElapsedTime);
            }
        }



        //TouchCollection _lastMouseState =new TouchCollection();
        //TouchCollection _currentMouseState = new TouchCollection();
        ///// <summary>
        /////   Helper for checking if a button was newly pressed during this update.
        ///// </summary>
        //public bool IsNewButtonPress()
        //{
        //    return (_lastMouseState.LeftButton == ButtonState.Pressed &&
        //            _currentMouseState.LeftButton == ButtonState.Released);
        //}

        //public bool IsNewButtonRelease()
        //{
        //    return (_lastMouseState.LeftButton == ButtonState.Released &&
        //            _currentMouseState.LeftButton == ButtonState.Pressed);
        //}


        Dictionary<int, FixedMouseJoint> fixedMouseJoints = new Dictionary<int, FixedMouseJoint>();
        Dictionary<int, Body> touchObjects = new Dictionary<int, Body>();
        private void processMouse()
        {
            TouchCollection _currentMouseState = Microsoft.Xna.Framework.Input.Touch.TouchPanel.GetState();

            foreach (TouchLocation location in _currentMouseState)
            {
                //foreach (TouchLocation location in _currentMouseState)
                //{
                //TouchLocation location = _currentMouseState.First();
                Vector2 position = ConvertUnits.ToSimUnits(location.Position);

                if (location.State == TouchLocationState.Pressed)
                {
                    Fixture savedFixture = World.TestPoint(position);
                    if (savedFixture != null)
                    {
                        Body body = savedFixture.Body;
                        FixedMouseJoint fmj = new FixedMouseJoint(body, position);
                        fmj.MaxForce = dragStrength * body.Mass;
                        fmj.UserData = location.Id;
                        World.AddJoint(fmj);
                        fixedMouseJoints.Add(location.Id, fmj);
                        body.Awake = true;
                    }
                    else
                    {
                        Body _circle = BodyFactory.CreateCircle(World, 0.3f, dragStrength / 500, position);
                        _circle.BodyType = BodyType.Dynamic;
                        //_circle.Mass = 3;
                        // _circle.LinearDamping = 2;

                        _circle.CollidesWith = Category.All;
                        _circle.CollisionCategories = Category.Cat10;
                        _circle.UserData = location.Id;
                        touchObjects.Add(location.Id, _circle);

                        //dragcircle = Util.createellipsetexture(new Size(ConvertUnits.ToDisplayUnits(0.3f * 2), ConvertUnits.ToDisplayUnits(0.3f * 2)));
                        //dragcircle.Tag = Microsoft.Xna.Framework.Vector2.Add(position, new Microsoft.Xna.Framework.Vector2(-dragcircle.Width / 2, -dragcircle.Height / 2));
                    }

                }

                //_circle = BodyFactory.CreateCircle(World, radius, 1f);
                //_circle.BodyType = BodyType.Dynamic;
                //_circle.Mass = 3;
                //_circle.LinearDamping = 2;
                //_circle.UserData = radius;
                //_circle.Position = ConvertUnits.ToSimUnits(new Microsoft.Xna.Framework.Vector2((float)Location.X, (float)Location.Y));


                if (location.State == TouchLocationState.Released)
                {
                    if (fixedMouseJoints.ContainsKey(location.Id))
                    {
                        World.RemoveJoint(fixedMouseJoints[location.Id]);
                        fixedMouseJoints[location.Id] = null;
                        fixedMouseJoints.Remove(location.Id);
                    }
                    if (touchObjects.ContainsKey(location.Id))
                    {
                        Body circ = touchObjects[location.Id];
                        touchObjects.Remove(location.Id);
                        circ.Dispose();
                        //dragcircle.Dispose();
                        //dragcircle = null;
                    }
                }
                else if (location.State == TouchLocationState.Moved)
                {
                    if (fixedMouseJoints.ContainsKey(location.Id))
                    {
                        fixedMouseJoints[location.Id].WorldAnchorB = position;
                    }
                    if (touchObjects.ContainsKey(location.Id))
                    {
                        touchObjects[location.Id].Position = position;

                        //dragcircle.Tag = Microsoft.Xna.Framework.Vector2.Add(ConvertUnits.ToDisplayUnits(position), new Microsoft.Xna.Framework.Vector2(-dragcircle.Width / 2, -dragcircle.Height / 2));
                    }

                }

            }
            if (_currentMouseState.Count == 0 && (fixedMouseJoints.Count > 0 || touchObjects.Count > 0))
            {
                foreach (Body obj in touchObjects.Values)
                {
                    Body circ = obj;
                    // touchObjects.Remove((int)obj.UserData);
                    circ.Dispose();
                }
                touchObjects.Clear();
                foreach (FixedMouseJoint fmj in fixedMouseJoints.Values)
                {
                    World.RemoveJoint(fmj);
                    // fixedMouseJoints[(int)fmj.UserData] = null;
                    //fixedMouseJoints.Remove((int)fmj.UserData);
                }
                fixedMouseJoints.Clear();
            }
            //_lastMouseState = _currentMouseState;
        }


        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.Black);

            // TODO: Add your drawing code here

            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);


            spriteBatch.Draw(backgroundTexture, App.ShakeImagePos, Color.White);
            //LineBatch.DrawLine(spriteBatch, Color.Red, App.ShakeImagePos, Vector2.Add( App.ShakeImagePos,new Vector2(backgroundTexture.Width,0)));
            //LineBatch.DrawLine(spriteBatch, Color.Red, App.ShakeImagePos, Vector2.Add(App.ShakeImagePos, new Vector2(0, backgroundTexture.Height)));
            //LineBatch.DrawLine(spriteBatch, Color.Red, Vector2.Add(App.ShakeImagePos, new Vector2(backgroundTexture.Width, 0)), Vector2.Add(App.ShakeImagePos, new Vector2(backgroundTexture.Width, backgroundTexture.Height)));
            //LineBatch.DrawLine(spriteBatch, Color.Red, Vector2.Add(App.ShakeImagePos, new Vector2(0, backgroundTexture.Height)), Vector2.Add(App.ShakeImagePos, new Vector2(backgroundTexture.Width, backgroundTexture.Height)));

            //Drawrectangle(App.ShakeImagePos, Vector2.Add(App.ShakeImagePos, new Vector2(backgroundTexture.Width, backgroundTexture.Height)));

            //spriteBatch.Draw(testTxt, ConvertUnits.ToDisplayUnits(_rectangle.Position),
            //                             null,
            //                              Color.White, _rectangle.Rotation, Vector2.Zero, 1, SpriteEffects.None, 0);
            //LineBatch.DrawLine(spriteBatch, Color.Red, ConvertUnits.ToDisplayUnits(joint.WorldAnchorA), ConvertUnits.ToDisplayUnits(joint.WorldAnchorB));
            //LineBatch.DrawLine(spriteBatch, Color.Green, new Vector2(40, 40), Vector2.Add(new Vector2(40, 40), World.Gravity));
            foreach (ShakeObjectCtl so in App.shakeObjects)
            {
                so.Render(spriteBatch);
            }
            int i;
            if (!MergeOverlay)
            {
                for (i = 0; i < maxTextCount; i++)
                {
                    foreach (ShakeObjectCtl so in App.shakeObjects)
                    {
                        double cnt = so.texturesList.Count;
                        if (((cnt / maxTextCount) * i) >= Math.Floor((cnt / maxTextCount) * i) && ((cnt / maxTextCount) * (i - 1)) < Math.Floor((cnt / maxTextCount) * i))
                            spriteBatch.Draw(so.texturesList[(int)Math.Floor((cnt / maxTextCount) * i)], (Vector2)so.texturesList[(int)Math.Floor((cnt / maxTextCount) * i)].Tag, Microsoft.Xna.Framework.Color.White);
                    }
                }
            }
            else
            {

                foreach (ShakeObjectCtl so in App.shakeObjects)
                {
                    for (i = 0; i < so.texturesList.Count; i++)
                    {
                        double cnt = so.texturesList.Count;

                        spriteBatch.Draw(so.texturesList[i], (Vector2)so.texturesList[i].Tag, Microsoft.Xna.Framework.Color.White);
                    }
                }
            }

            //foreach (ShakeObjectCtl so in App.shakeObjects)
            //{
            //    //spriteBatch.Draw(so.circle, (Vector2)so.texturesList[0].Tag, Microsoft.Xna.Framework.Color.White);
            //    spriteBatch.Draw(so.circle, (Vector2)so.circle.Tag, Microsoft.Xna.Framework.Color.White);
            //}

            //if (dragcircle != null) 
            //{
            //    spriteBatch.Draw(dragcircle, (Vector2)dragcircle.Tag, Microsoft.Xna.Framework.Color.White);
            //}
            GameTime gt = new GameTime(e.TotalTime, e.ElapsedTime);

            // AdRotatorXNAComponent.Current.Draw(gt);

            spriteBatch.End();
            //ROT//components.Draw(e.ElapsedTime, e.TotalTime);
            if (App.IsTrial)
            {
                AdComponent.Current.Draw();
            }
        }
        //Texture2D dragcircle;

        void Drawrectangle(Vector2 p1, Vector2 p2)
        {
            Texture2D rect = new Texture2D(SharedGraphicsDeviceManager.Current.GraphicsDevice, (int)(p2.X - p1.X), (int)(p2.Y - p1.Y));

            Color[] data = new Color[rect.Width * rect.Height];
            for (int i = 0; i < rect.Width; ++i) data[i] = Color.Red;
            for (int i = rect.Width * (rect.Height - 1); i < rect.Width * rect.Height; ++i) data[i] = Color.Red;
            for (int i = 0; i < rect.Width * rect.Height; i = i + rect.Width) data[i] = Color.Red;
            for (int i = rect.Width - 1; i < rect.Width * rect.Height; i = i + rect.Width) data[i] = Color.Red;
            rect.SetData(data);

            Vector2 coor = p1;
            spriteBatch.Draw(rect, p1, Color.White);

        }

        void startstop(bool command)
        {
            // If the accelerometer is null, it is initialized and started
            if (AccelerometerHelper.Instance.Active == false && command == true)
            {
                //// Instantiate the accelerometer sensor object
                //accelerometer = new Accelerometer();

                //// Add an event handler for the ReadingChanged event.
                //accelerometer.ReadingChanged += new EventHandler<AccelerometerReadingEventArgs>(accelerometer_ReadingChanged);

                //// The Start method could throw and exception, so use a try block
                //try
                //{
                //    textBlock2.Text = "starting accelerometer";
                //    accelerometer.Start();
                //}
                //catch (AccelerometerFailedException exception)
                //{
                //    textBlock2.Text = "error starting accelerometer";
                //}

                AccelerometerHelper.Instance.Active = true;


                accelerometerLastTick = DateTime.UtcNow.Ticks;

            }
            else if (command == false)
            {
                // if the accelerometer is not null, call Stop
                //try
                //{
                //    accelerometer.Stop();
                //    accelerometer = null;
                //    textBlock2.Text = "accelerometer stopped";
                //}
                //catch (AccelerometerFailedException exception)
                //{
                //    textBlock2.Text = "error stopping accelerometer";
                //}
                AccelerometerHelper.Instance.Active = false;
            }
        }
        Simple3DVector previousReading;


        private void OnAccelerometerHelperReadingChanged(object sender, AccelerometerHelperReadingEventArgs e)
        {

            //e.RawAcceleration.ToString();
            //e.LowPassFilteredAcceleration.ToString();
            //e.OptimalyFilteredAcceleration.ToString();
            //e.AverageAcceleration.ToString();
            Simple3DVector acc = e.LowPassFilteredAcceleration;
            if (previousReading == null) previousReading = acc;
            Dispatcher.BeginInvoke(() =>
            {

                double accdelta = GetAccelerometerDelta();
                //double magnitude = Math.Abs(acc.Magnitude - previousReading.Magnitude);
                //if (magnitude > 0.05 && accdelta > 0)
                //{
                //    System.Windows.Point pnt = new System.Windows.Point(Math.Abs(acc.X) * magnitude * 1000 * (acc.X - previousReading.X) / accdelta, Math.Abs(acc.Y) * magnitude * 1000 * (acc.Y - previousReading.Y) / accdelta);
                if (double.IsInfinity(acc.X))
                {
                    return;
                }

                //textBlock2.Text = String.Format("{0}\n{1}\n{2}\n{3}", acc.Magnitude.ToString(), pnt.X.ToString("0.00"), pnt.Y.ToString("0.00"), acc.Z.ToString("0.00"));
                //Canvas.SetLeft(this, Canvas.GetLeft(this) + (pnt.X - ImageDragPoint.X));
                //Canvas.SetTop(this, Canvas.GetTop(this) + (pnt.Y - ImageDragPoint.Y));
                //foreach (ShakeObject obj in App.shakeObjects)
                //{
                //    obj.Move(acc);
                //}
                //}

                World.Gravity = new Vector2((float)acc.X * gravityRatio, -(float)acc.Y * gravityRatio);
                previousReading = acc;

            }
            );
        }
        float gravityRatio = 100f;

        long accelerometerLastTick;

        private double GetAccelerometerDelta()
        {
            long tick = DateTime.UtcNow.Ticks;
            double accdelta = new TimeSpan(tick - accelerometerLastTick).TotalSeconds;
            accelerometerLastTick = tick;
            return accdelta;
        }

    }
}